﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.GUI.Common;
using SiGeSIB.Data.Finances;
using SiGeSIB.Data.Management;
using SiGeSIB.Data.Common;
using SiGeSIB.Services;
using SiGeSIB.Data.Security;

namespace SiGeSIB.GUI.Finances
{
#if DESIGN
	public partial class FEditCostCenter : FormRedirector.FEditCostCenter
#else
	public partial class FEditCostCenter : FGenericEditor<CostCenter>
#endif
	{
		#region Constructors
		public FEditCostCenter()
			: base(EFormState.View, -1)
		{ }
		public FEditCostCenter(EFormState initialState, int id)
			: base(initialState, id)
		{
			InitializeComponent();

			#region State Step
			InitialState = initialState;
			if (initialState == EFormState.View)
			{
				this.Text = "Edição de Centro de Custo";
				_IdleMessage = "Visualize as informações do centro de custo";
			}
			else
			{
				this.Text = "Inserção de Centro de Custo";
				_IdleMessage = "Insira as informações do centro de custo.";
			}
			#endregion

			#region FieldsToLock
			FieldsToLock =
				new List<object>()
				{
					lblCode,
					lblContributors,
					lblDescription,
					lblName,
					txtCode,
					txtDescription,
					txtName,
					cboContributors
				};
			#endregion

			#region Controller
			_Controller.AddErrorLabel("InvalidName", new Control[] { lblName, txtName });
			_Controller.AddErrorLabel("InvalidCode", new Control[] { lblCode, txtCode });
			#endregion
		} 
		#endregion

		#region Properties
		protected override bool HasEditPermission
		{
			get
			{
				return
					Manager.Instance.LoggedUser.IsAdmin
					||
					(
						Manager.Instance.LoggedUser.Permissions
						&
						EPermissions.ManageCostCenter
					) != EPermissions.None;
			}
		}
		#endregion

		#region Methods
		#region Auxiliares
		private void _FillContributorsComboBox(List<Contributor> contributors)
		{
			List<KeyValuePair<string, int>> values = null;

			if (contributors != null)
			{
				values = new List<KeyValuePair<string, int>>();

				foreach (Contributor c in contributors)
					values.Add(new KeyValuePair<string, int>(c.Name, c.Id));
			}

			_AlreadyLoaded = true;

			cboContributors.DataSource = values;
			cboContributors.ValueMember = "Value";
			cboContributors.DisplayMember = "Key";
			cboContributors.SelectedIndex = -1;
		}
		#endregion

		#region Overridens
		public override bool ConflictsWith(ConflictableForm form)
		{
			bool conflicts = false;

			if (form.GetType() == this.GetType())
			{
				// Só conflita se for inserção ou se for edição do mesmo elemento
				FEditCostCenter fEdit = form as FEditCostCenter;

				if (fEdit.InitialState == this.InitialState)
				{
					if (this.InitialState == EFormState.Edit)
						conflicts = true;
					else if (this._CurrentEntity != null && fEdit._CurrentEntity != null && this._CurrentEntity.Id == fEdit._CurrentEntity.Id)
						conflicts = true;
				}
			}

			return conflicts;
		}

		#region Loading
		protected override CostCenter _LoadEntity(int id)
		{
			IFinancesServicesProvider servProv = _Manager.ServicesProvider.CreateFinancesServicesProvider();
			return servProv.GetCostCenter(id, CostCenterInfo.GeneralData);
		}

		protected override void _FillEntity(CostCenter entity)
		{
			if (entity != null)
			{
				txtCode.Text = entity.Code;
				txtDescription.Text = entity.Description;
				txtName.Text = entity.Name;
				cboContributors.SelectedValue = entity.ResponsableId;
			}
			else
			{
				txtCode.Text = null;
				txtDescription.Text = null;
				txtName.Text = null;
				cboContributors.SelectedValue = -1;
			}
		}

		protected override object _LoadSpecificData()
		{
			IManagementServicesProvider manProv = _Manager.ServicesProvider.CreateManagementServicesProvider();
			return manProv.GetContributors(EContributorType.Member);
		}

		protected override void _FillSpecificData(object result)
		{
			if (!_AlreadyLoaded)
				_FillContributorsComboBox(result as List<Contributor>);
		}
		#endregion

		#region Commit
		protected override CostCenter _BuildEntity()
		{
			CostCenter center = new CostCenter();

			center.Id = _Id;
			center.Code = txtCode.Text;
			center.Description = txtDescription.Text;
			center.Name = txtName.Text;
			if (cboContributors.SelectedItem != null)
				center.ResponsableId = (int)cboContributors.SelectedValue;

			return center;
		}

		protected override ExceptionsContainer _ValidateEntity(CostCenter entity)
		{
			ExceptionsContainer exs = new ExceptionsContainer();

			if (string.IsNullOrEmpty(entity.Code))
				exs.Add(new ValidationError("InvalidCode", "O código do centro de custo é de preenchimento obrigatório."));

			return exs;
		}

		protected override int _SaveEntity(CostCenter entity)
		{
			IFinancesServicesProvider finProv = _Manager.ServicesProvider.CreateFinancesServicesProvider();
			int id = entity.Id;

			if (entity.Id > 0)
				finProv.UpdateCostCenter(entity);
			else
				id = finProv.InsertCostCenter(entity);

			return id;
		} 
		#endregion
		#endregion	 
		#endregion
	}
}
